<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="选择仓库"
        >
          <j-dict-select-tag v-decorator="['warehouse', validatorRules.warehouse]" @change="handleWarehouseFlag" placeholder="指定门店使用" :type="'radioButton'"
                             :triggerChange="true" dictCode="warehouse"/>
        </a-form-item>
<!--        <a-form-item label="库存地点" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--          <a-select-->
<!--            style="width: 100%"-->
<!--            placeholder="请选择"-->
<!--            optionFilterProp = "children"-->
<!--            v-model="selectedStock"-->
<!--            :getPopupContainer= "(target) => target.parentNode">-->

<!--            <a-select-option v-for="(item,roleindex) in stockList" :key="roleindex.toString()" :value="item.id">-->
<!--              {{item.lgobe}}-->
<!--            </a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="库存地点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-auto-complete
            v-model="selectedStock"
            :data-source="productSnDataSource"
            @select="onSelect"
            placeholder="请选择库存地点"
            :filter-option="filterOption"
          />
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {postAction,getAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import JDate from '@/components/jeecg/JDate'
import SelectStoreModal from '../../stm/modules/SelectStoreModal'
import JSelectProduct from '@/components/jeecgbiz/JSelectProduct'
import {queryallV2 } from '@/api/api'


export default {
  components: {
    JDate,
    SelectStoreModal,
    JSelectProduct
  },
  name: 'StmRequiregoodsModal',
  data() {
    return {
      storeName:"",
      productSnDataSource:[],
      title: '操作',
      visible: false,
      model: {},
      selectStoreValue: [],
      selectStoreOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      moment,
      format: 'YYYY-MM-DD HH:mm:ss',
      disableSubmit: false,
      mainId: '',
      hiding: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        productSn: { rules: [{ required: true, message: '请选择商品!' }] },
        warehouse: { rules: [{ required: true, message: '请选择仓库!' }] },
      },
      url: {
        add: '/sms/smsStoreGifts/addSmsStoreGiftsGrant', //点击下面新增后 确认按钮接口
        applyOAUrl: "/stm/stmReplenishmentV2/push-oa", //要货推送到oa
        applyOAUrlRetreat: "/stm/stmRetreat/push-oa", //退仓推送到oa
        storeIdList:"/stm/stmStoreInfo/list",
      },
      stockList:[],
      selectedStock:[],
      selectedStockId:"",
      dataResult:[],
      lgobeList:[],
      stockType:""
    }
  },
  created() {
    // getAction(this.url.storeIdList,{ pageNo: 1, pageSize:100 }).then(res => {
    //   console.log('678');
    //   console.log(res);
    //   if(res.success){
    //     this.dataResult = res.result.records;
    //     // this.productSnDataSource =  [... new Set(res.result.records.map(data => (data['name'])))];
    //     this.productSnDataSource = this.lgobeList
    //   }else{
    //     console.log(res.message);
    //   }
    // })
  },
  methods: {
    onSelect(value){
      this.selectedStock = value
      this.selectedStockId = this.stockList.filter(i => i.lgobe == value)[0].id
      console.log('22222');
      console.log(this.stockList);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLocaleLowerCase().indexOf(input.toLocaleLowerCase()) >= 0
      );
    },
    add(mainId) {
      console.log('54');
      console.log(mainId);
      if (mainId) {
        this.edit({ mainId }, '')
        console.log('1222222');
      } else {
        this.$message.warning('请选择一条数据')
      }
    },
    detail(record) {
      this.edit(record, 'd')
    },
    edit(record, v) {
      if (v == 'e') {
        this.hiding = false;
        this.disableSubmit = false;
      } else if (v == 'd') {
        this.hiding = false;
        this.disableSubmit = true;
      } else {
        this.hiding = true;
        this.disableSubmit = false;
      }
      this.form.resetFields()
      this.mainId = record.mainId
      this.model = Object.assign({}, record)
      this.visible = true
      console.log('232323');

      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'couponId','giftId','grantGroup', 'grantUuid', 'expireDays', 'frozenDays', 'storePosition','productSn','count'))
        // 时间格式化
        // this.form.setFieldsValue({ startTime: this.model.startTime ? moment(this.model.startTime) : null })
        // this.form.setFieldsValue({ endTime: this.model.endTime ? moment(this.model.endTime) : null })
      })
      if(this.model.count === null  || this.model.count === '' || this.model.count === undefined){
        this.model.count = 1;
      }
    },
    handleSource(res,type){
      this.sourceResult = res
      this.stockType = type
    },
    close() {
      this.$emit('close')
      this.selectedStock = [];
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.add
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          let params = {
            id: Number(this.model.mainId),
            inOutAddressCode: this.selectedStockId, // 调出/调入库存地点:根据b仓和c仓，选择不同的值
            inOutCode: that.model.warehouse         //b仓1000，c仓1010
          };
          const newUrl = that.stockType == 'TC'?that.url.applyOAUrlRetreat:that.url.applyOAUrl
          postAction(newUrl, params).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          });
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleWarehouseFlag (e) {
      this.model.warehouseFlag = e;
      this.selectedStock = []
      this.lgobeList = []
      this.stockList = []
      for (var a = 0; a < this.sourceResult.result[e].length; a++) {
        this.lgobeList.push(this.sourceResult.result[e][a].lgobe)
      }
      this.stockList = this.sourceResult.result[e] //库存地点接口值
      this.productSnDataSource = this.lgobeList //库存地点的数据源
      // 得到所有的库存地点的name
      console.log('1->',this.lgobeList);
      console.log('2->',this.stockList);


    },
  }
}
</script>

<style scoped>

</style>
